import React, { Component } from 'react'
import {
  Card,
  Table,
  Button,
  message,
  Modal,
  Form,
  Input} from 'antd'
import { PlusOutlined , ArrowRightOutlined, DownloadOutlined} from '@ant-design/icons'

import LinkButton from '../../components/link-button'
import {reqCategorys,reqAddCategory,reqUpdateCategory} from '../../api'

const { Item } = Form
// 商品路由
export default class Category extends Component {

  constructor (props) {

    super(props)

    this.state = {
      category: {},
      categorys: [], //一级分类数据
      subCategorys: [], //二级分类数据
      loadingFlg: false, // 等待状态flg
      parentId: '0',
      parentName: '', //父分类名称
      showModal: 0, //确认框的显示情况 0为都不显示 1显示添加 2显示修改
      url: 'http://localhost:5000/manage/operate/download',
      buttonDisabled: true,
      pageName: "品类管理",
    }

    // 修改表单的ref
    this.formRef = React.createRef()
    // 新增表单的ref
    this.formRef2 = React.createRef()
  }

    // 下载execl
    downloadExecl = () => {
      const eleLink = document.createElement('a');
      eleLink.style.display = 'none';
      // eleLink.target = "_blank"
      eleLink.href = this.state.url;
      // eleLink.href = record;
      document.body.appendChild(eleLink);
      eleLink.click();
      document.body.removeChild(eleLink);
    }

    // ajax获得一级分类的数据
    getCategorys = async () => {

      // 发送ajax请求前loading
      this.setState({loadingFlg: true})
      const result = await reqCategorys('0')
      // 请求结束后取消loading
      this.setState({loadingFlg: false})
      const {data, status} = result.data
      if (status === 0) {
        // 更新状态
        this.setState({categorys: data.categorys, buttonDisabled: false})
      } else if (status === 2) {
        message.error("您没有使用" + this.state.pageName + "的权限")
      } else {
        message.error(result.data.message)
      }
    }

    // 获取二级分类的数据
    showSubCategorys = async (category) => {
      // 获取id
      const {id,categoryName} = category
      // 发送ajax请求前loading
      this.setState({loadingFlg: true})
      // 发送ajax请求去根据id获取二级列表数据
      const result = await reqCategorys(id)
      // 请求结束后取消loading
      this.setState({loadingFlg: false})
      const {data,status,message} = result.data
      if (status === 0) {
        // 更新状态
        this.setState({subCategorys: data.categorys, parentId: id, parentName: categoryName, category})
      } else {
        message.error(message)
      }
    }

    // 组件加载之后获取数据
    componentDidMount () {
      // table数据的ajax取得
      this.getCategorys()
    }

    // 展示添加对话框
    showAddModal = () => {
      this.setState({showModal:1})
      if (this.formRef2.current) {
        this.formRef2.current.setFieldsValue({addModal:''})
      }
    }

    // 点击取消的回调函数
    handleCancel = () => {
      this.setState({showModal: 0})
    }

    // 增加分类的回调函数
    addCategory = async () => {
      this.setState({showModal: 0})
      const {addModal} = this.formRef2.current.getFieldsValue('addModal')
      // 发送ajax请求前loading
      this.setState({loadingFlg: true})
      const result = await reqAddCategory(addModal, this.state.parentId)
      // 请求结束后取消loading
      this.setState({loadingFlg: false})
      
      const {status} = result.data
      if (status === 0) {
        // 判断当前是一级还是二级列表并检索
        if (this.state.parentId === '0') {
          this.getCategorys()
        } else {
          this.showSubCategorys(this.state.category)
        }
      } else {
        message.error(result.data.message)
      }
      
    }

    // 更新分类的回调函数
    updateCategory = async () => {
      this.setState({showModal: 0})
      const {updateModal} = this.formRef.current.getFieldsValue('updateModal')
      // 发送ajax请求前loading
      this.setState({loadingFlg: true})
      const result = await reqUpdateCategory({categoryId:this.categoryId, categoryName: updateModal, parentId: this.state.parentId})
      // 请求结束后取消loading
      this.setState({loadingFlg: false})

      const {status} = result.data

      if (status === 0) {
        // 判断当前是一级还是二级列表并检索
        if (this.state.parentId === '0') {
          this.getCategorys()
        } else {
          this.showSubCategorys(this.state.category)
        }
      } else {
        message.error(result.data.message)
      }
    }

    // 修改分类信息
    showUpdate = (category) => {
      this.category = category
      this.setState({showModal: 2})
      if (this.formRef.current) {
        this.formRef.current.setFieldsValue({updateModal:category.name})
      }
      this.categoryId = category.id
    }

    render() {

        const {parentId,parentName,categorys,subCategorys,showModal,buttonDisabled} = this.state
        // 获取分类名称
        const category = this.category || {}

        // 分类信息
        this.columns = [
          { title: '分类名称', dataIndex: 'categoryName'},
          {
            title: '操作',
            width: 350,
            render: (category) => (
              <span>
                <LinkButton onClick={() => this.showUpdate(category)}>修改分类名</LinkButton>
                {parentId === '0' ? <LinkButton onClick={() => this.showSubCategorys(category)}>查看子分类</LinkButton> : null}
              </span>
            ),
          },
        ]

        // 表格数据
        const dataSource = parentId === '0' ? categorys : subCategorys

        // 按钮
        const extra = (
          <div>
            <Button onClick={this.showAddModal} disabled={buttonDisabled} type="primary" icon={<PlusOutlined />} style={{marginRight:10}}>
                添加分类
            </Button>
            <Button onClick={this.downloadExecl} disabled={buttonDisabled} type="primary" icon={<DownloadOutlined />}>
                导出至Execl
            </Button>
          </div>   
        )

        // 标题
        const title = parentId === '0' ? '一级分类列表' : (
          <span>
            <LinkButton onClick={() => {this.setState({parentId:'0'})}}>一级分类列表</LinkButton>
            <ArrowRightOutlined style={{color: 'black',fontSize: '12px',marginLeft: 5,marginRight: 8}}/>
            <span>{parentName}</span>
          </span>
          )

        return (
            <Card title={title} extra={extra} style={{ width: 1680 ,height: 900}}>
                <Table rowKey="id" columns={this.columns} dataSource={dataSource}
                  bordered
                  pagination={{defaultPageSize:10,showQuickJumper:true}}
                  loading={this.state.loadingFlg}/>

            <Modal title="添加分类信息"
              visible={showModal === 1}
              onOk={this.addCategory}
              onCancel={this.handleCancel}
              cancelText={'取消'}
              okText={'确认'}> 
              <Form ref={this.formRef2} layout="vertical">
                <Item label="所属分类" tooltip="您要添加的分类">
                  <Input value={parentId === '0' ? '一级分类' : parentName} disabled={true}></Input>
                </Item>
                <Item name='addModal' label="分类名称" initialValue="">
                    <Input placeholder='请输入分类名称' onPressEnter={this.addCategory}></Input>
                </Item>
              </Form>
            </Modal>

            <Modal title="修改分类信息"
              visible={showModal === 2}
              onOk={this.updateCategory}
              onCancel={this.handleCancel}
              cancelText={'取消'}
              okText={'确认'}>
              <Form ref={this.formRef}>
                <Item name='updateModal' label="分类名称" initialValue={category.name}>
                  <Input allowClear={true} onPressEnter={this.updateCategory}></Input>
                </Item>
              </Form>
            </Modal>
            </Card>
        )
    }
}
